using Nop.Core.Domain.Customers;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Nop.Core.Domain.Catalog
{
    public static class ProductVariantExtensions
    {
        public static int[] ParseRequiredProductVariantIds(this ProductVariant productVariant)
        {
            if (productVariant == null)
                throw new ArgumentNullException("productVariant");

            if (String.IsNullOrEmpty(productVariant.RequiredProductVariantIds))
                return new int[0];

            var ids = new List<int>();

            foreach (var idStr in productVariant.RequiredProductVariantIds
                .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                .Select(x => x.Trim()))
            {
                int id = 0;
                if (int.TryParse(idStr, out id))
                    ids.Add(id);
            }

            return ids.ToArray();
        }

		public static TierPrice GetPreferredTierPrice(this ProductVariant productVariant, ICollection<CustomerRoleMapping> roles)
		{
			if (productVariant == null)
				throw new ArgumentNullException("productVariant");

			if (roles == null || roles.Count == 0 || !productVariant.HasTierPrices)
				return null;

			var availableRoles = roles.Where(role=> ( role.StartDate==null || role.StartDate<DateTime.UtcNow ) && (role.EndDate == null || role.EndDate> DateTime.UtcNow));
			var tierPrices = productVariant.TierPrices.Where(tp => availableRoles.Any(role => role.Id == tp.CustomerRoleId));
			if (tierPrices.Any())
			{
				return tierPrices.FirstOrDefault(p => p.Price == tierPrices.Min(tp => tp.Price));
			}
			return null;
		}
    }
}
